package com.book.config;

import com.book.filter.UserIdAuthenticationFilte;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author yicheng
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserIdAuthenticationFilte userIdAuthenticationFilte;
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;


//    创建BCryptPasswordEncoder注入容器，这是security密码加密规则，需要什么就配置什么
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //取消security默认的放行限制，配置自己需要放行的接口
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭crsf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口，允许匿名访问
                .antMatchers("/login","/getCaptcha","/register","/book/list","/book/getClasses","/book/getById",
                        "/loadImg/*","/apply/getFirst","/apply/getSecond","/notice/getList","/post/getList"
                        ,"/post/getOne","/carousel/getCarousel","/loginAdmin").permitAll()

                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
//        把jwtAuthenticationTokenFilter这个过滤器放在security提供的UsernamePasswordAuthenticationFilter过滤器之前调用
        //把自定义的jwt过滤器添加到security的过滤器链中，并且是添加到UsernamePasswordAuthenticationFilter这个过滤器之前。
        http.addFilterBefore(userIdAuthenticationFilte, UsernamePasswordAuthenticationFilter.class);

        //配置异常处理器
        http.exceptionHandling()
                //配置用户认证失败处理-登录失败
                .authenticationEntryPoint(authenticationEntryPoint);

        //允许跨域
        http.cors();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
